package cn.edu.scau.cmi.xiaowenyang.hibernate.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import cn.edu.scau.cmi.xiaowenyang.hibernate.domain.Student;
import cn.edu.scau.cmi.xiaowenyang.hibernate.domain.Teacher;

public class TeacherDAO extends HibernateSessionImpl {

	public static final String NAME = "name";

	public void save(Teacher transientInstance) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.save(transientInstance);
		transaction.commit();
		session.close();
	}

	public void delete(Teacher persistentInstance) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(persistentInstance);
		transaction.commit();
		session.close();
	}

	public void update(Teacher Teacher) {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.update(Teacher);
		transaction.commit();
		session.close();
	}

	public List<Teacher> findAll() {
		Session session = getSession();
		String queryString = "select * from Teacher";
		Query queryObject = session.createSQLQuery(queryString).addEntity(Teacher.class);
		List<Teacher> list = queryObject.list();
		session.close();
		return list;
	}

	public List findAllStudents(Teacher persistentInstance) {
		// System.out.println(persistentInstance.getId().toString());
		String queryString = "select * from student inner join teacher on student.tutor = teacher.id where teacher.id="
				+ persistentInstance.getId().toString();
		Query queryObject = getSession().createSQLQuery(queryString).addEntity(Student.class);
		return queryObject.list();
	}
}
